package org.geektimes.projects.user.validator.bean.validation.annotations;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * custom phone number validator implement
 *
 * @author biwin
 * @see ConstraintValidator
 */
public class PhoneValidAnnotationValidator implements ConstraintValidator<PhoneValid, CharSequence> {

    private static final Logger logger = Logger.getLogger(PhoneValidAnnotationValidator.class.getName());

    private int min;
    private int max;

    @Override
    public void initialize(PhoneValid phoneValid) {
        this.min = phoneValid.min();
        this.max = phoneValid.max();
        this.validateParameters();
    }

    private void validateParameters() {
        if (this.min != 11 || this.max != 11) {
            logger.severe("the phone number must be 11 digits!");
        }
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null || value.length() != 11) {
            return false;
        } else {
            String regex = "^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])" +
                    "|(19[8|9]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            return p.matcher(value).matches();
        }
    }
}
